package com.renrenyou.duanshipin.util;

import android.content.ContentValues;
import android.content.Context;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;

import com.renrenyou.duanshipin.net.IFileDownloadCallback;
import com.renrenyou.duanshipin.net.MyOkhttp;
import com.renrenyou.duanshipin.widget.UpgradProgressView;

import java.io.File;

import okhttp3.Call;

public class DownloadFileUtil {

    private static final String mFilePath = Environment.getExternalStorageDirectory().getPath() + "/Download";

    public static Call downloadFile(Context context, String url, UpgradProgressView progressView) {
        String path = mFilePath + File.separator + System.currentTimeMillis() + ".mp4";
        return MyOkhttp.getInstance().get(url, new IFileDownloadCallback(path) {
            @Override
            public void onStart() {

            }

            @Override
            public void onProgress(long current, long total) {
                progressView.setProgress((int) (100 * current / total));
            }

            @Override
            public void downloadSuccess(File file) {
                ToastUtil.showToast(context, "下载成功，文件保存在" + path);
                progressView.setVisibility(View.INVISIBLE);
                notifyMp4update(file, context);
            }

            @Override
            public void failure(int errorCode, String errorMsg) {
                ToastUtil.showToast(context, errorMsg);
            }
        });
    }

    private static void notifyMp4update(File file, Context context) {
        if (file == null) {
            return;
        }
        ContentValues contentValues = new ContentValues();
        contentValues.put(MediaStore.Video.Media.DATA, file.getAbsolutePath());
        contentValues.put(MediaStore.Video.Media.DISPLAY_NAME, file.getName());
        contentValues.put(MediaStore.Video.Media.MIME_TYPE, "video/mp4");

        Uri uri = context.getContentResolver().insert(MediaStore.Video.Media.EXTERNAL_CONTENT_URI, contentValues);
        if (uri != null) {
            Log.d("downloadFile", "视频保存成功: ");
        } else {
            Log.d("downloadFile", "视频保存失败: ");
        }
    }
}
